<template>
  <el-card shadow="never" class="card">
    <template #header>
      <div>{{ articleForm.id ? "编辑" : "新增" }}文章</div>
    </template>
    <el-form
      ref="articleFormRef"
      :inline="true"
      :model="articleForm"
      :rules="articleFormRules"
      label-width="120"
    >
      <el-form-item
        style="width: 65%"
        label-width="80"
        label="文章标题"
        prop="article_title"
      >
        <el-input
          v-model="articleForm.article_title"
          placeholder="请输入文章标题"
          clearable
          maxlength="55"
          @change="articleTitleVAlidate"
        />
      </el-form-item>
      <el-form-item style="width: 25%" v-if="getUserInfo?.id">
        <div class="publish-btn">
          <el-button
            type="danger"
            size="small"
            @click="publish(articleFormRef)"
            >{{ articleForm.id ? "修改文章" : "发布文章" }}</el-button
          >
        </div>
      </el-form-item>
      <el-form-item style="width: 100%; height: auto" prop="article_content">
        <MdEditor
          v-model="articleForm.article_content"
          @onUploadImg="onUploadImg"
        />
      </el-form-item>
    </el-form>
    <el-dialog
      title="发布文章"
      v-model="dialogVisible"
      :width="800"
      draggable
      :fullscreen="true"
      :before-close="closeDialog"
    >
      <el-form
        ref="dialogArticleFormRef"
        :inline="true"
        :model="articleForm"
        :rules="dialogArticleFormRules"
        label-width="120"
      >
        <el-form-item
          class="form-item100"
          label="文章标题"
          prop="article_title"
        >
          {{ articleForm.article_title }}
        </el-form-item>
        <el-form-item
          class="form-item100"
          label="文章描述"
          prop="article_description"
        >
          <el-input
            v-model="articleForm.article_description"
            placeholder="..."
            style="width: 70%"
            clearable
            type="textarea"
            maxlength="150"
            resize="none"
            :autosize="{ minRows: 2, maxRows: 3 }"
            show-word-limit
          />
        </el-form-item>
        <el-form-item class="form-item100" label="文章分类" prop="category_id">
          <el-select
            v-model="articleForm.category_id"
            :style="{ width: '380px' }"
            placeholder="请选择分类"
            filterable
            clearable
            allow-create
            @change="categoryChange"
          >
            <el-option
              v-for="item in categoryOptionList"
              :key="item.value"
              :label="item.value"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item class="form-item100" label="文章标签" prop="tagIdList">
          <el-select
            v-model="articleForm.tagIdList"
            :style="{ width: '380px' }"
            placeholder="请选择标签"
            multiple
            filterable
            clearable
            allow-create
            :multiple-limit="3"
            @change="tagChange"
          >
            <el-option
              v-for="item in tagOptionList"
              :key="item.value"
              :label="item.value"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          class="article-cover"
          label="文章缩略图"
          prop="article_cover"
        >
          <UploadFile :type="4" v-model:imageUrl="articleForm.article_cover" @upload-success="uploadCallback" />
        </el-form-item>
        <el-form-item label="置顶">
          <el-switch
            v-model="articleForm.is_top"
            size="small"
            active-text="是"
            inactive-text="否"
            :active-value="1"
            :inactive-value="2"
          />
        </el-form-item>
        <el-form-item
          v-if="articleForm.is_top == 1"
          label="排序"
          prop="order"
        >
          <el-input-number
            v-model="articleForm.order"
            placeholder="请输入排序"
            style="width: 20%"
            :min="1"
            :max="9999"
            :precision="0"
            :controls="false"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="articleForm.status">
            <el-radio :label="1">公开</el-radio>
            <el-radio :label="2">私密</el-radio>
            <el-radio :label="3">草稿箱</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="文章类型">
          <el-radio-group v-model="articleForm.type">
            <el-radio :label="1">原创</el-radio>
            <el-radio :label="2">转载</el-radio>
            <el-radio :label="3">翻译</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          v-if="[2, 3].includes(Number(articleForm.type))"
          label="原文链接"
          prop="origin_url"
        >
          <el-input
            v-model="articleForm.origin_url"
            placeholder="请输入原文链接"
            style="width: 80%"
            clearable
            type="textarea"
            maxlength="225"
            resize="none"
            :autosize="{ minRows: 2, maxRows: 4 }"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button size="small" @click="closeDialog()">取消</el-button>
        <el-button
          size="small"
          type="danger"
          plain
          @click="submitForm(dialogArticleFormRef, 1)"
        >
          保存草稿
        </el-button>
        <el-button
          size="small"
          type="danger"
          @click="submitForm(dialogArticleFormRef, 2)"
        >
          {{ articleForm.id ? "修改文章" : "发布文章" }}
        </el-button>
      </template>
    </el-dialog>
    <el-dialog v-model="coverPreviewVisible">
      <img :src="coverUrl" alt="Preview Image" />
    </el-dialog>
  </el-card>
</template>

<script lang="ts" setup>
import { MdEditor } from "md-editor-v3";
import "md-editor-v3/lib/style.css";
import { ref, onMounted, reactive } from "vue";
import { useRoute, useRouter } from "vue-router";
import {
  insertBlog,
  updateBlog,
  queryBlogById,
  titleExist,
  queryBlogCategoryList,
  queryBlogTagList,
} from "@/api/blog";
import { tagV, coverV } from "./validator";
import { ElNotification } from "element-plus";
import { user } from "@/store";
import UploadFile from "@/components/UploadFile/index.vue";
import { uploadImageToOss } from "@/utils/tools";
import { storeToRefs } from "pinia";
const userStore = user();
const authorName = userStore.getUserInfo?.username || null;
const { getUserInfo } = storeToRefs(userStore);
const dialogVisible = ref(false);
const articleFormRef = ref();
const dialogArticleFormRef = ref();
const route = useRoute();
const router = useRouter();
const canPublish = ref<boolean>(true);
const origin_title = ref<string>("");
interface ArticleForm {
  id: number;
  article_title: string;
  categoryName: string;
  authorName: string;
  category_id: number|null;
  tagIdList: number[];
  tagNameList: string[];
  userId: number;
  article_content: string;
  article_cover: string;
  is_top: 1 | 2; // 置顶 1 置顶 2 取消置顶
  order: number; // 置顶文章的排序
  status: 1 | 2 | 3; // 状态 公开 私密 回收站
  type: 1 | 2 | 3; // 类型 原创 翻译 转载
  origin_url: string; // 原文链接 翻译或转载才需要填
  article_description: string; // 文章描述
}

const articleForm = reactive<ArticleForm>({
  id: 0,
  article_title: "",
  categoryName: "",
  authorName: "",
  category_id: null,
  tagIdList: [],
  tagNameList: [],
  userId: 0,
  article_content: "",
  article_cover: "",
  is_top: 2,
  order: 1,
  status: 1,
  type: 1,
  origin_url: "",
  article_description: "",
});

const tagOptionList = ref<Tag[]>([]);
const categoryOptionList = ref<Tag[]>([]);

const coverPreviewVisible = ref(false);
const coverUrl = ref<string>("");

// 校验规则
const articleFormRules = reactive({
  article_title: {
    required: true,
    trigger: "blur",
    message: "请输入文章标题",
  },
  article_content: {
    required: true,
    message: "请输入文章内容",
    trigger: "blur",
  },
});
// 校验规则
const dialogArticleFormRules = reactive({
  category_id: {
    required: true,
    message: "请选择文章分类",
    trigger: ["change"],
  },
  article_description: {
    required: true,
    message: "请输入文章描述",
    trigger: ["blur"],
  },
  tagIdList: {
    required: true,
    message: "请选择文章标签",
    validator: tagV,
    trigger: ["change"],
  },
  article_cover: {
    required: true,
    message: "请上传文章封面",
    validator: coverV,
    trigger: ["change"],
  },
  origin_url: {
    required: true,
    message: "请输入原文链接",
    trigger: ["blur"],
  },
  order: {
    validator: (rule: any, value: any, callback: Function) => {
      if (!value) {
        callback(new Error("请输入文章排序"));
      } else {
        articleForm.order = value - 0;
        callback();
      }
    },
    trigger: "blur",
  },
});

const closeDialog = () => {
  dialogVisible.value = false;
};

const resetForm = (formEl: any) => {
  console.log(formEl, "el");
  if (!formEl) return;
  if (formEl.hasOwnProperty("resetFields")) {
    formEl.resetFields();
  }
};

// 选择类型
const categoryChange = (e: number) => {
  console.log(e, "categoryChange");
};
// 标签选择
const tagChange = (e: number[]) => {
  console.log(e, "tagChange");
};
// md图片上传回调
async function onUploadImg(files: File[], callback: Function) {
  const result = await Promise.all(
    files.map((file: File) => {
      return uploadImageToOss(file, 4);
    })
  );
  console.log(result);
  callback(result);
}

// 缩略图上传回调
const uploadCallback = (url: string) => {
  articleForm.article_cover = url;
};
// 发布文章 打开弹窗
async function publish(formEl: any) {
  if (!formEl) return;
  if (!canPublish.value) {
    ElNotification.warning({
      title: "Failed",
      message: "标题重复，请更换标题",
      offset: 100,
    });
    return;
  }
  await formEl.validate((valid: any) => {
    if (valid) {
      dialogVisible.value = true;
    } else {
      ElNotification.warning({
        title: "Warning",
        message: "请按照提示填写信息",
        offset: 100,
      });
    }
  });
}

async function articleTitleVAlidate(title: string) {
  if(origin_title.value && title == origin_title.value) {
    canPublish.value = true;
    return
  }
  try {
    const res = await titleExist(title);
    if (res.data) {
      canPublish.value = false;
      ElNotification.warning({
        title: "Warning",
        message: "标题重复，请更换标题",
        offset: 100,
      });
    } else {
      canPublish.value = true;
    }
  } catch (error) {
    console.log(error);
  }
}

// 整理文章的数据返回给后端
function arrangeArticle(articleForm: ArticleForm) {
  const restArticle = articleForm;

  const category= categoryOptionList.value.find(
    (category) => (category.id = restArticle.category_id || 0)
  );
  const tempTagNameList: string[] = [];
  tagOptionList.value.map((item: Tag) => {
    if (restArticle.tagIdList.includes(item.id)) {
      tempTagNameList.push(item.value);
    }
  });

  restArticle.categoryName = category?.value || "";
  restArticle.tagNameList = tempTagNameList;
  restArticle;
  if (!restArticle.id) {
    restArticle.userId = getUserInfo.value?.id;
    restArticle.authorName = authorName;
  }
  if (restArticle.type == 1) {
    restArticle.origin_url = "";
  }
  return restArticle;
}

// 发布
async function submitForm(formEl: any, type: number) {
  await formEl.validate(async (valid: any) => {
    if (valid) {
      if (type == 1) {
        // 1 是保存草稿 2 是直接发布
        articleForm.status = 3;
      }

      if (articleForm.is_top == 2) {
        articleForm.order = 1;
      }
      // 整合数据
      const finalArticle = arrangeArticle(articleForm);
      let res;
      if (!finalArticle.id) {
        // 新增
        res = await insertBlog(finalArticle);
      } else {
        // 编辑
        res = await updateBlog(finalArticle);
      }
      if (res.data == "创建成功") {
        ElNotification.success({
          title: "Success",
          message: "发布成功",
          offset: 100,
        });
        // resetForm(formEl.value);
        if (articleFormRef.value) {
          resetForm(articleFormRef.value);
        }
        dialogVisible.value = false;
        setTimeout(() => {
          router.push("/blog");
        }, 300);
      } else {
        ElNotification.error({
          title: "Failed",
          message: "发布博客失败",
          offset: 100,
        });
      }
    } else {
      ElNotification.warning({
        title: "Warning",
        message: "请按照提示填写信息",
        offset: 100,
      });
    }
  });
}
interface Tag {
  id: number;
  value: string;
}
// 获取标签列表
async function getCategory() {
  try {
    const { data } = await queryBlogCategoryList();
    categoryOptionList.value = data;
  } catch (error) {
    ElNotification.error({
      message: "获取标签列表失败",
      duration: 1000,
      title: "Failed",
    });
  }
}
// 获取分类列表
async function getTag() {
  try {
    const { data } = await queryBlogTagList();
    tagOptionList.value = data;
  } catch (error) {
    ElNotification.error({
      message: "获取分类列表失败",
      duration: 1000,
      title: "Failed",
    });
  }
}
// 根据id获取文章详情
async function getArticleDetailsById(id: number) {
  try {
    const res:any = await queryBlogById({ id });
    if (res.status == 200) {
      const { likes, comments, stars, view_times, userId, comment_times, ...data } = res.data
      data.tagNameList = data?.tagNameList.split(",") || [];
      data.tagIdList = data?.tagIdList.split(",").map((item: string) => {
        return Number(item);
      }) || [];
      Object.assign(articleForm, data);
      origin_title.value = articleForm.article_title;
    } else {
      ElNotification.error({
        message: "获取文章详情失败",
        duration: 1000,
      });
    }
  } catch (error) {
    ElNotification.error({
      message: "获取文章详情失败",
      duration: 1000,
    });
  }
}

onMounted(async () => {
  resetForm(articleFormRef.value);
  await getTag();
  await getCategory();
  const articleId = route.query.articleId;
  if (!articleId) return;
  // 根据id获取文章信息
  getArticleDetailsById(Number(articleId));
});
</script>
<style lang="scss" scoped>
.card {
  height: calc(100vh - 110px);
  overflow: hidden;
}
.publish-btn {
  display: flex;
  align-items: center;
  flex-wrap: nowrap;
}

.flex_r {
  display: flex;
  justify-content: flex-start;
  flex-wrap: wrap;
}

.form-item {
  &45 {
    width: 45%;
    font-weight: bold;
  }

  &100 {
    width: 100%;
    font-weight: bold;
  }
}

:deep(.el-select-dropdown__item) {
  padding: 0 5px;
}

:deep(.el-dialog.is-fullscreen) {
  width: 800px;
  overflow-y: auto;
  overflow-x: hidden;
}

:deep(.el-dialog__footer) {
  position: absolute;
  bottom: 0;
  right: 5%;
}

.md-editor {
  height: calc(100vh - 260px);
}

.article-cover {
  :deep(.el-form-item__content) {
    width: 260px !important;
    height: 150px !important;
  }

  :deep(.el-upload-list__item) {
    width: 260px !important;
    height: 150px !important;
    margin: 0 !important;
    border: none !important;
  }

  :deep(.el-upload--picture-card) {
    width: 260px !important;
    height: 150px !important;
  }

  :deep(.el-upload-list--picture-card) {
    width: 260px !important;
    height: 150px !important;
    margin: 0 !important;
    border: none !important;
  }
}
</style>
